/**
 * @Title:  MainActivity.java 
 * @Copyright:  XXX Co., Ltd. Copyright YYYY-YYYY,  All rights reserved 
 * @Description:  TODO<请描述此文件是做什么的> 
 * @author:  MeiYi 
 * @data:  2016-2-23 下午5:12:01 
 * @version:  V1.0 
 */

package artid.com.arttogoa;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.xutils.x;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.http.RequestParams;
import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.NormalItem;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.CameraUtils;
import artid.com.arttogoa.util.GsonUtils;
import artid.com.arttogoa.util.IdCheckUtil;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.RegexUtil;
import artid.com.arttogoa.view.MyEditText;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.VolleyError;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * TODO<实名认证>
 * 
 * @author 熊彬
 * @data: 2016-2-23 下午5:12:01
 * @version: V1.0
 */
public class RealNameAuthenticationActivity extends BaseActivity implements
OnClickListener {
	private Button mNext;
	private TextView mJump;
	private Intent in;
	private ImageView  idCardZimg, idCardFimg,
	idCardPerimg;
	private LinearLayout idCardZLL,idCardFLL,idCardPerLL,idCardZ,idCardF,idCardPer;
	String path, urlup, urldown, urlall;
	Boolean isRegister = false;//是否是从注册一步步走来的（默认false）
	private int type;
	private MyEditText realname, realid;
	private Bitmap clipBitmap;//剪裁之后的图片
	private Boolean IDCardisEmploy=false;//身份证是否可以使用
	private String pushMessageID;//推送消息的ID
	private List<String> photoPath_list;//剪裁之后的图片路径
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.example.artworkarta.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_real_name_authentication_one);
		ArtWorkApp.getInstance().addActivity(this);
		setContent(this, getIntent());
		initData();
	}

	/**
	 * 
	 */
	private void initData() {
		mContext = this;
		isRegister=getIntent().getBooleanExtra("isRegister", false);
		path = Environment.getExternalStorageDirectory()+ "/YJZ/IDCard.png";
		File file = new File(path);
		if (file.exists()){
			file.delete();
		}
		mNext = (Button) findViewById(R.id.RealNameAuthentication_btn_real_next);
		mTittle = (TextView) findViewById(R.id.title_text);
		mFbText = (TextView) findViewById(R.id.title_fb);
		if(isRegister==true){
			mFbText.setText("跳过");
			mFbText.setTextColor(this.getResources().getColor(R.color.jump));
			mFbText.setVisibility(View.VISIBLE);
		}
		mBack = (ImageView) findViewById(R.id.back_btn);
		idCardZ = (LinearLayout) findViewById(R.id.RealNameAuthentication_idcardz);
		idCardF = (LinearLayout) findViewById(R.id.RealNameAuthentication_idcardf);
		idCardPer = (LinearLayout) findViewById(R.id.RealNameAuthentication_idcardper);
		idCardZimg = (ImageView) findViewById(R.id.RealNameAuthentication_idcardz_img);
		idCardFimg = (ImageView) findViewById(R.id.RealNameAuthentication_idcardf_img);
		idCardPerimg = (ImageView) findViewById(R.id.RealNameAuthentication_idcardper_img);
		realname = (MyEditText) findViewById(R.id.RealNameAuthentication_realname);
		realname.addTextChangedListener(mTextWatcherIDCode);
		realid = (MyEditText) findViewById(R.id.RealNameAuthentication_realid);
		realid.addTextChangedListener(mTextWatcherIDCode);
		idCardZLL=(LinearLayout) findViewById(R.id.RealNameAuthentication_ll_ID_positive);
		idCardFLL=(LinearLayout) findViewById(R.id.RealNameAuthentication_ll_ID_back);
		idCardPerLL=(LinearLayout) findViewById(R.id.RealNameAuthentication_ll_ID_head);
		mNext.setOnClickListener(this);
		mFbText.setOnClickListener(this);
		mBack.setOnClickListener(this);
		idCardZLL.setOnClickListener(this);
		idCardFLL.setOnClickListener(this);
		idCardPerLL.setOnClickListener(this);
		mBack.setVisibility(View.VISIBLE);
		mTittle.setText("实名认证");
		photoPath_list=new ArrayList<String>();
		//提交条件判断是否完全
		ValidationInformation();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back_btn:
			finish();
			break;
		case R.id.title_fb:
			in = new Intent(mContext, ImproveInformationActivity.class);
			in.putExtra("isRegister", isRegister);
			startActivity(in);
			break;
		case R.id.RealNameAuthentication_btn_real_next:
			submitReal();
			break;
		case R.id.RealNameAuthentication_ll_ID_positive:
			//身份证正面
			type = 1;
			showPopupWindow();
			break;
		case R.id.RealNameAuthentication_ll_ID_back:
			//身份证背面
			type = 2;
			showPopupWindow();
			break;
		case R.id.RealNameAuthentication_ll_ID_head:
			//身份证头部照
			type = 3;
			showPopupWindow();
			break;

		default:
			break;
		}

	}


	/**
	 * 对身份证号的验证
	 */
	TextWatcher mTextWatcherIDCode = new TextWatcher() {  
		private CharSequence temp;  
		@Override  
		public void onTextChanged(CharSequence s, int start, int before, int count) {  
			// TODO Auto-generated method stub  
			temp = s;  
		}  

		@Override  
		public void beforeTextChanged(CharSequence s, int start, int count,  
				int after) {  
			// TODO Auto-generated method stub  
			//		          mTextView.setText(s);//将输入的内容实时显示  
		}  

		@Override  
		public void afterTextChanged(Editable s) {  
			// TODO Auto-generated method stub   
			if (temp.length() ==18) {
				checkIdentity();
			}
			ValidationInformation();
		}  
	};  

	/**
	 * 验证信息
	 */
	private void ValidationInformation(){
		//提交条件判断是否完全
		if(RegexUtil.checkRealName(realname.getText().toString()) && IdCheckUtil.IDCardValidate( realid.getText().toString()) && IDCardisEmploy!=false &&
				!StringUtils.isEmpty(urlup) && !StringUtils.isEmpty(urldown) && !StringUtils.isEmpty(urlall) ){
			mNext.setEnabled(true);
			mNext.setBackgroundResource(R.drawable.red_frame);
		}else{
			//条件不成立
			mNext.setEnabled(false);
			mNext.setBackgroundResource(R.drawable.zjm_bg_dl);
		}
	}

	/**
	 * 上传实名认证信息
	 */
	private void submitReal() {
		VolleyBasic.showLoding(this);
		RequestParams params=new RequestParams(Cache.certification);
		params.addHeader("Accept",  "application/json, text/javascript, */*");
		params.addParameter("realname", realname.getText().toString());
		params.addParameter("identity", realid.getText().toString());
		params.addParameter("urlup", urlup);
		params.addParameter("urldown", urldown);
		params.addParameter("urlall", urlall);
		params.addParameter("token", AppUtil.getUser().getToken());
		params.setConnectTimeout(60000);
		x.http().post(params, new CommonCallback<String>() {

			@Override
			public void onCancelled(CancelledException cex) {
				// TODO Auto-generated method stub
				System.out.println("主动停止网络请求");
				VolleyBasic.disMissLoding();
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				// TODO Auto-generated method stub
				//请求错误
				if(isOnCallback==false){
					//ex异常信息不是来自回调方法
					System.out.println("ex异常信息不是来自回调方法："+ex.getMessage());
				}else{
					//ex异常信息是来自回调方法
					System.out.println("ex异常信息是来自回调方法："+ex.getMessage());
				}
				VolleyBasic.disMissLoding();
			}

			@Override
			public void onFinished() {
				// TODO Auto-generated method stub
				System.out.println("请求完毕,不管成功失败");
			}

			@Override
			public void onSuccess(String result) {
				// TODO Auto-generated method stub
				//成功
				VolleyBasic.disMissLoding();
				Log.d("log", "Post请求结果："+result);
				String code=GsonUtils.message(result, "ret");
				String message=GsonUtils.message(result, "msg");
				if("1".equals(code)){
					//记住审核状态,只要上传成功就是认证中
					AppUtil.getUser().setIs_auth("2");
					if(isRegister==true){
						in = new Intent(mContext,ImproveInformationActivity.class);
						in.putExtra("isRegister", true);
						in.putExtra("isFillInAutonym", true);
						startActivity(in);
					}else{
						//判断是否是推送消息进入的
						if(getIntent().getBooleanExtra("isPush", false)==true){
							//判断是否是推送消息进入的
							ArtWorkApp.getInstance().RemoveActivity("MainActivity");
							ArtWorkApp.getInstance().exit();
							in = new Intent(mContext,RealNameAuthenticationTwoActivity.class);
							startActivity(in);
						}else{
							in = new Intent(mContext,RealNameAuthenticationTwoActivity.class);
							startActivity(in);
							finish();
						}
					}
					if(photoPath_list!=null && photoPath_list.size()!=0){
						for (int i = 0; i < photoPath_list.size(); i++) {
							BitmapUtil.deleteBitmap(photoPath_list.get(i).toString());
						}
					}
				}else if("0".equals(code)){
					showToast(message);
				}else if("-99".equals(code)){
					VolleyBasic.showRemoteLoginDialog(RealNameAuthenticationActivity.this);
				}
			}
		});
	}



	/**
	 * 检验身份证是否存在
	 */
	private void  checkIdentity(){
		VolleyBasic.getInstance(RealNameAuthenticationActivity.this).post(
				Cache.checkIdentity,
				VolleyMap.getInstance().checkIdentity(realid.getText().toString()), NormalItem.class, new VolleyCallback() {
					@Override
					public void onSuccess(VolleyData vd) {
						IDCardisEmploy=true;
						ValidationInformation();
					}

					@Override
					public void onError(VolleyError volleyError) {
						IDCardisEmploy=false;
						showToast("检验身份证是否存在失败");
						ValidationInformation();
					}
				});
	}

	// 点击头像，选择照片
	public void showPopupWindow() {
		AlertUtils.initPhotoAlertDialog(mContext,Integer.parseInt(NetUtils.getDisplayMetrics(RealNameAuthenticationActivity.this).get(NetUtils.DM_WIDTH)), new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (v.getId()) {
				case R.id.tv_phone:
					//检查权限
					if (ContextCompat.checkSelfPermission(RealNameAuthenticationActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
						displayFrameworkBugMessageAndExit();
						return;
					}
					//照相机	
					CameraUtils.openCameraImage(RealNameAuthenticationActivity.this);
					AlertUtils.dismiss();
					break;
				case R.id.tv_choice:
					//从相册获取
					CameraUtils.openLocalImage(RealNameAuthenticationActivity.this);
					AlertUtils.dismiss();
					break;
				default:
					break;
				}
			}
		});
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
		// TODO Auto-generated method stub  
		super.onActivityResult(requestCode, resultCode, data);  
		if (requestCode == CameraUtils.GET_IMAGE_BY_CAMERA) {
			final Uri uri=CameraUtils.imageUriFromCamera;
			if(uri != null) {
				/*锐哥让去掉剪裁
				Intent i=new Intent(mContext,Clip_Activity.class);
				i.putExtra("ImagePath",  BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
				 */
				try {
					getBitmap(BitmapUtil.getSmallBitmap(BitmapUtil.UriConversionAbsoluteURL(mContext, uri), 500, 500));
				} catch (Exception e) {
					// TODO: handle exception
				}
			}else{
				//防止文件不会立马创建
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						if(uri != null) {
							/*锐哥让去掉剪裁
							Intent i=new Intent(mContext,Clip_Activity.class);
							i.putExtra("ImagePath", BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
							startActivityForResult(i, 200);
							 */
						}
					}
				}, 1000);
			}
		} else if (requestCode == CameraUtils.GET_IMAGE_FROM_PHONE) {
			//判断是否从相册中获取图片
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				/*锐哥让去掉剪裁
				Intent i=new Intent(mContext,Clip_Activity.class);
				i.putExtra("ImagePath", BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
				 */
				getBitmap(BitmapUtil.getSmallBitmap(BitmapUtil.UriConversionAbsoluteURL(mContext, uri), 500, 500));
			}
		} else if(requestCode==200){
			/*锐哥让去掉剪裁
			if(data!=null){
				//获取剪切后的图片路径
				String PhotoPath=data.getExtras().getString("PhotoPath");  
				photoPath_list.add(PhotoPath);
				if(!StringUtils.isEmpty(PhotoPath)){
					clipBitmap=BitmapUtil.getSmallBitmap(PhotoPath, 500, 500);
					//设置图片
					if (type == 1) {
						idCardZimg.setVisibility(View.VISIBLE);
						idCardZimg.setBackgroundDrawable(BitmapUtil.bitmapToDrawable(clipBitmap));
						idCardZ.setVisibility(View.GONE);
						urlup = BitmapUtil.bitmaptoString(clipBitmap);
					} else if (type == 2) {
						idCardFimg.setVisibility(View.VISIBLE);
						idCardFimg.setBackgroundDrawable(BitmapUtil.bitmapToDrawable(clipBitmap));
						idCardF.setVisibility(View.GONE);
						urldown = BitmapUtil.bitmaptoString(clipBitmap);
					} else if (type == 3) {
						idCardPerimg.setVisibility(View.VISIBLE);
						idCardPerimg.setBackgroundDrawable(BitmapUtil.bitmapToDrawable(clipBitmap));
						idCardPer.setVisibility(View.GONE);
						urlall = BitmapUtil.bitmaptoString(clipBitmap);
					}
					ValidationInformation();
				}
			}
			 */
		}
	}

	private void getBitmap(Bitmap mBitmap){
		if(mBitmap!=null){
			if (type == 1) {
				idCardZimg.setVisibility(View.VISIBLE);
				idCardZimg.setImageBitmap(mBitmap);
				idCardZ.setVisibility(View.GONE);
				urlup = BitmapUtil.bitmaptoString(mBitmap);
			} else if (type == 2) {
				idCardFimg.setVisibility(View.VISIBLE);
				idCardFimg.setImageBitmap(mBitmap);
				idCardF.setVisibility(View.GONE);
				urldown = BitmapUtil.bitmaptoString(mBitmap);
			} else if (type == 3) {
				idCardPerimg.setVisibility(View.VISIBLE);
				idCardPerimg.setImageBitmap(mBitmap);
				idCardPer.setVisibility(View.GONE);
				urlall = BitmapUtil.bitmaptoString(mBitmap);
			}
			ValidationInformation();
		}
		Log.d("log", "第1张图："+urlup);
		Log.d("log", "第2张图："+urldown);
		Log.d("log", "第3张图："+urlall);
	}


	/**
	 * 保存裁剪之后的图片数据
	 *
	 * @param picdata
	 */
	private void setPicToView(Intent picdata) {
		Bundle extras = picdata.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			Log.e("path", "photone" + photo);
			Drawable drawable = new BitmapDrawable(photo);
			// TODO 保存用户真实头像
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
			byte[] b = stream.toByteArray();
			try {

				Log.e("dream1", "缩略图的路径：" + path);
				File file = new File(path);
				FileOutputStream fileStream = new FileOutputStream(file);

				fileStream.write(b);
				fileStream.flush();
				fileStream.close();
				Log.e("dream2", "缩略图的大小：" + fileStream.toString().length());

			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	/**
	 * 若摄像头被占用或者摄像头有问题则跳出提示对话框
	 */
	private void displayFrameworkBugMessageAndExit() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.app_name));
		builder.setMessage("请设置开启摄像头权限");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				NetUtils.getAppDetailSettingIntent(mContext);
			}
		});
		builder.show();
	}
}
